/******************************************************************************\
    StdFileEx.hpp contains a class of std file object with advanced reading.
    Copyright (C) 2008  Victor Vinogradov (fly3333@gmail.com)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/

#ifndef __STD_FILE_EX_HPP
#define __STD_FILE_EX_HPP

#include ".\StdFile.hpp"
#include <string>
#include ".\KMP.h"
#include ".\Memory.hpp"

class cStdFileEx : public cStdFile
{
public:
	std::string GetLine( const std::string &delim = "\n", int max_length = -1 )
	{
		std::string result;
		cMemory< int > next( delim.length() + 1 );
		PreKMP( delim.c_str(), ( int )delim.length(), next );
		for( int delim_i = 0, ch, length = 0; delim_i < ( int )delim.length() && length != max_length && ( ch = GetChar() ) != EOF; ++delim_i, ++length )
		{
			result.push_back( ( char )ch );
			while( delim_i >= 0 && ( char )ch != delim[ delim_i ] )
				delim_i = next[ delim_i ];
		}
		return result;
	}
	std::string GetWord( const std::string &blanks = " \r\n\t", int max_word_length = -1, int max_read_length = -1 )
	{
		std::string result;
		bool is_blank[ 256 ];
		memset( is_blank, 0, sizeof( is_blank ) );
		for( int i = 0; i < ( int )blanks.length(); ++i )
		{
			is_blank[ ( unsigned char )blanks[ i ] ] = true;
		}
		int ch;
		int read_length = 0;
		while( read_length != max_read_length && ( ch = PeekChar() ) != EOF && is_blank[ ch ] )
		{
			GetChar();
			++read_length;
		}
		while( ( int )result.length() != max_word_length && read_length != max_read_length && ( ch = PeekChar() ) != EOF && !is_blank[ ch ] )
		{
			result.push_back( ( char )GetChar() );
			++read_length;
		}
		return result;
	}
};

#endif
